<template>
  {{ carouselId }}

  <el-button :icon="Plus" type="primary" @click="addBtnFun">添加</el-button>
  <el-button @click="bigdel" type="danger">批量删除</el-button>
  <el-table
    ref="multipleTableRef"
    :data="listone"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column label="图片">
      <template #default="scope">
        <!-- {{ scope.row }} -->
        <img class="scopeimg" :src="scope.row.carouselUrl" alt="" />
      </template>
    </el-table-column>
    <el-table-column label="跳转链接">
      <template #default="scope">
        <!-- {{ scope.row.redirectUrl }} -->
        <el-text class="mx-1" type="primary">{{
          scope.row.redirectUrl
        }}</el-text>
      </template>
    </el-table-column>

    <el-table-column prop="carouselRank" label="排序"></el-table-column>
    <el-table-column prop="createTime" label="添加时间"></el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <!-- {{ scope.row.redirectUrl }} -->
        <el-button
          size="small"
          type="success"
          @click="handleEditor(scope.$index, scope.row)"
        >
          修改
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    @current-change="currentChange"
    background
    layout="prev, pager, next"
    :total="total"
  />

  <!-- 弹框 -->
  <el-dialog v-model="dialogFormVisible" @closed="closed" :title="title" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="跳转连接" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          action="http://backend-api-02.newbee.ltd/manage-api/v1/upload/file"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :headers="{ Token }"
        >
          <img
            v-if="ruleForm.imageUrl"
            :src="ruleForm.imageUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="跳转连接" prop="href">
        <el-input v-model="ruleForm.href" />
      </el-form-item>
      <el-form-item label="排序值" prop="rank">
        <el-input v-model="ruleForm.rank" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="dialogFormVisible = false;carouselId=''">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
let Token = localStorage.getItem("token");
let carouselId="";// 存放id

import { onMounted, ref, reactive } from "vue";
import { ElTable, ElMessage } from "element-plus";
import axios from "../../ajax";
import { Plus,Message } from "@element-plus/icons-vue";


let title = ref("添加");//动态标题默认添加

const multipleTableRef = ref();//绑定表单id
const multipleSelection = ref([]);//选中数据
const handleSelectionChange = (val) => {// 选中数据方法
  multipleSelection.value = val;
};
onMounted(() => {//挂载完成之后
  getdata(1);
});
let listone = ref([]);
let total = ref(0);//总条数
let getdata = async (pageNumber) => {  // 分页封装
  let { list, totalCount } = await axios.get("/carousels", {
    params: {
      pageNumber,
      pageSize: 10,
    },
  });
  listone.value = list;
  total.value = totalCount;
};
let currentChange = (page) => {// 切换分页
  getdata(page);
};
// *****************************************下面是删除************************************
let getid = async (ids) => {
  let res = await axios.delete("/carousels", {
    data: {
      ids,
    },
  });
};
let handleDelete = (i, row) => {//*********删除一个******* */
  listone.value.splice(i, 1);
  getid([row.carouselId]);
};
let bigdel = () => {//批量删除多个*******************************************************
  multipleSelection.value.map(item=>{//选中数据
     listone.value.map((items,index)=>{// 原本10条数据
         if(item.carouselId==items.carouselId){
           listone.value.splice(index,1)
         }
     })
  })   
};

const dialogFormVisible = ref(false); // 弹框默认不显示********************************
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  href: "",
  rank: "",
  imageUrl: "",
});

let addBtnFun = () => {//增加按钮提交事件
  dialogFormVisible.value = true;
  title.value = "添加";
   carouselId="";// 存放id
  ruleForm.href = "";
  ruleForm.rank = "";
  ruleForm.imageUrl = "";
};

const rules = reactive({
  // 验证
  href: [{ required: true, message: "跳转连接不能为空", trigger: "blur" }],
  rank: [{ required: true, message: "排序值不能为空", trigger: "blur" }],
  imageUrl: [{ required: true, message: "图片不能为空", trigger: "blur" }],
});

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // ajax
      dialogFormVisible.value = false;
      
      console.log("submit!");
      if (title.value == "添加") {
        submitFun();
      } else {
        editorFun()
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

let submitFun = async () => {// 增加操作
  let res = await axios.post("/carousels", {
    carouselRank: ruleForm.rank,
    carouselUrl: ruleForm.imageUrl,
    redirectUrl: ruleForm.href,
  });
 
  getdata(1);
};
let  editorFun=async ()=>{// 编辑
      let res=await axios.put("/carousels",{
        carouselRank: ruleForm.rank,
       carouselUrl: ruleForm.imageUrl,
        redirectUrl: ruleForm.href,
        carouselId
      })
      carouselId=""
      getdata(1);
}

// 图片上传

// const imageUrl = ref('')

const beforeAvatarUpload = (rawFile) => {
  // 图片大小验证
  console.log(rawFile.type);
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png"
  ) {
    return true;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  } else {
    ElMessage.error("图片格式不正确!");
    return false;
  }
  // return true
};
const handleAvatarSuccess = (
  //上传成功
  response,
  uploadFile
) => {
  ruleForm.imageUrl = response.data;
};


// 修改
let handleEditor = (index, row) => {
  // console.log(row);
  title.value = "修改";
  dialogFormVisible.value = true;
  ruleForm.rank = row.carouselRank;// 数据回显
  ruleForm.href = row.redirectUrl;// 数据回显
  ruleForm.imageUrl = row.carouselUrl;// 数据回显
  carouselId=row.carouselId
};


let closed=()=>{
     carouselId=""
}
</script>
<style lang="scss" scoped>
.scopeimg {
  width: 20px;
  height: 20px;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  line-height: 100px;
  border: 1px dashed #999;
  text-align: center;
  font-size: 50px;
  color: #999;
  &:hover {
    border: 1px dashed red;
    color: red;
  }
  img {
    width: 100%;
    height: 100px;
  }
}
</style>